import WS from './ws'
import store from '@/store'
import extend from 'extend'
import { util } from 'dtc'
import app from '../../assets/js/app'
const wsUrl = 'webSocketUrl' // 可改为真实的websocket 接口
let wsConnection,
  cashData = []
// 成功之后的数据处理 -可根据具体 数据格式进行处理
const handleData = (v, currentPth) => {
  if (v.code != 200) {
    wsConnection.closeConnect()
    wsConnection = null
    cashData = []
    return
  }
  if (util.isArray(v.data)) {
    cashData = [...v.data]
    let dataSet = extend(
      true,
      {},
      cashData.find(item => item.path == currentPth)
    )
    store.commit('setDataSet', dataSet)
    // app.$emit('dataReady')
  }
  if (util.isPlainObject(v.data)) {
    for (let key in v.data) {
      let value = v.data[key]
      if (value == name || value == path) continue
      for (let k of cashData) {
        if (cashData[k].path == v.data.path) {
          extend(true, item, v.data)
          break
        }
      }
    }
    if (currentPth == store.state.path) {
      store.commit('updateDataSet', v.data)
    }
  }
}
// 链接websocket
const connected = (path = '/') => {
  if (wsConnection) return
  wsConnection = new WS({
    url: wsUrl,
    successHandler: v => {
      handleData(v, path)
    },
    errorHandler: () => {
      console.log('ws_Error')
    }
  })
}
// 页面切换时 会调用 数据源的init方法
const init = (path = '/') => {
  if (wsConnection) {
    let dataSet = extend(true, {}, cashData.find(item => item.path == path))
    store.commit('setDataSet', dataSet)
  } else {
    connected(path)
  }
  app.log('websocket init')
}
const destroy = () => {
  try {
    wsConnection.closeConnect()
    wsConnection = null
    cashData = []
  } catch (e) {}
  app.log('websocket destroy')
}
export { init, destroy }
